-- 食人花类
local Plant = require("app.mode.Plant")
local AniHelper = require("app.utils.AnimateHelper")

local Chomper = {}
setmetatable(Chomper, Plant)
Chomper.__index = Chomper

Chomper.IDLE = 0
Chomper.EATING = 1

function Chomper:initView()
    if self:getState() == Chomper.IDLE then
        self._sprite, self._animate = AniHelper("plants/", self:getName())
    elseif self:getState() == Chomper.EATING then
        self._sprite, self._animate = AniHelper("plants/", self:getName() .. "_digest")
    end
end

-- 重写功能函数
function Chomper:doFunc()
    -- 由咀嚼状态变为空闲状态
    if self:getState() == Chomper.EATING then
        local sprite
        sprite, self._animate = AniHelper("plants/", self:getName())
        self._sprite:setTexture(sprite:getTexture())
        self:runAnimate()

        self:setState(Chomper.IDLE)
    end
end

-- 被攻击
function Chomper:beAttack(attack)
    if self:getState() == Chomper.IDLE then
        self:stopAnimate()

        local sprite, target

        local function attackFinish(node, data)
            sprite, self._animate = AniHelper("plants/", self:getName() .. "_digest")
            self._sprite:setTexture(sprite:getTexture())
            self:runAnimate()
        end

        sprite, self._animate = AniHelper("plants/", self:getName() .. "_attack", 0.1, 1)
        self._sprite:setTexture(sprite:getTexture())
        self._sprite:runAction(cc.Sequence:create(self._animate, cc.CallFunc:create(attackFinish), nil))

        -- 移除僵尸
        target = self:getTarget()[1]
        if target then
            self:removeTarget(target)
            -- self._scene:removeZombie(target)
            target:preRemove()
            target:removeSelf()
        end

        -- 置为咀嚼状态，同时计时清零
        self:setState(Chomper.EATING)
        self._time = 0
    elseif self:getState() == Chomper.EATING then
        -- 咀嚼状态和其它植物一样受攻击
        Plant.beAttack(self, attack)
    end
end

function Chomper:setPosition(x, y)
    if self._sprite then
        if type(x) == "table" then
            self._sprite:setPosition(x.x + 30, x.y + 10)
        elseif type(x) == "number" and type(y) == "number" then
            self._sprite:setPosition(x + 30, y + 10)
        end
    end
end

function Chomper:getSize()
    local w, h = Plant.getSize(self)
    return w - 40, h-20
end

function Chomper:getState()
    return self._data.state
end

function Chomper:setState(val)
    self._data.state = val
end

function Chomper:isReady()
    return self._data.state == Chomper.IDLE
end

return Chomper
